
package com.jf.cloud.payment.controller;

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.jf.cloud.common.constant.PayType;
import com.jf.cloud.payment.bo.RefundInfoResultBO;
import com.jf.cloud.payment.manager.PayManager;
import com.jf.cloud.payment.model.RefundInfo;
import com.jf.cloud.payment.service.RefundInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Hidden;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 退款成功通知，目前只有微信会有退款的回调
 * @author zz
 */
@Hidden
@RestController
@RequestMapping("/ua/notice/refund")
public class RefundNoticeController {

    @Autowired
    private PayManager payManager;

    @Autowired
    private RefundInfoService refundInfoService;

    /**
     * 退款结果通知
     */
    @RequestMapping("/order/{payType}")
    public ResponseEntity<String> result(HttpServletRequest request, @RequestBody(required = false) String data, @PathVariable Integer payType) throws WxPayException {
        RefundInfoResultBO refundInfoResultBO = payManager.validateAndGetRefundInfo(request, PayType.instance(payType), data);
        // 如果是预售订单，此处会有两个,此时会有两种情况
        // 情况1，都是微信支付此时只需要退款成功即可
        // 情况2，其中一个是余额支付or支付宝支付的，因为这俩也都是直接成功没有回调，所以同上
        RefundInfo refundInfo = refundInfoService.listByRefundIdAndWxPay(refundInfoResultBO.getRefundId());
        if (!refundInfoResultBO.getRefundSuccess()) {
            if (StrUtil.isNotBlank(refundInfo.getCallbackContent())) {
                refundInfo.setCallbackContent(refundInfoResultBO.getCallbackContent());
                refundInfo.setCallbackTime(new Date());
                refundInfoService.updateByIdPayId(refundInfo);
            }
            return ResponseEntity.ok(refundInfoResultBO.getSuccessString());
        }
        refundInfoService.refundSuccess(refundInfo);
        return ResponseEntity.ok(refundInfoResultBO.getSuccessString());
    }

}
